package com.skydroid.fpvplayerdemo

import android.Manifest
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.Button
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import com.skydroid.fpvplayer.*
import java.nio.ByteBuffer


class MainActivity : AppCompatActivity() {
    var fpvWidget:FPVWidget? = null
    var mapWidget:View? = null
    var switchVideoMapLayout:FrameLayout? = null

    var liveStreamHelper = LiveStreamHelper()

    var mp4RecordHelper = MP4RecordHelper()

    val liveStreamListener = LiveStreamListener { status, timestamp_us ->
        MyLogger.kLog().e("直播流状态：${status} ${timestamp_us}")
    }

    var isLiveStart = false

    var isStartRecord = false
    var btnRecordVideo:Button? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val settings = Settings(applicationContext)
        //去掉标题栏
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.activity_main)
        fpvWidget = findViewById<FPVWidget>(R.id.fpvWidget)
        mapWidget = findViewById<View>(R.id.map)
        switchVideoMapLayout = findViewById(R.id.switch_video_map)
        btnRecordVideo = findViewById(R.id.btnRecordVideo)
        findViewById<View>(R.id.btnUrl).setOnClickListener {
            var lastUrl = settings.lastUrl
            if (TextUtils.isEmpty(lastUrl)){
                lastUrl = Settings.C10
            }
            InputUrlDialogFragment.createDialog("确定",{
                _,_,url ->
                if (TextUtils.isEmpty(url)){
                    return@createDialog
                }
                settings.lastUrl = url
                fpvWidget?.url = url
                fpvWidget?.stop()
                fpvWidget?.start()
            },"取消",{
                _,_,_ ->
            },lastUrl).show(supportFragmentManager,"action_url")
        }

        findViewById<View>(R.id.btnPushVideo).setOnClickListener {
            val lastPushUrl = settings.lastPushUrl
            val pb = if (isLiveStart){
                "停止直播"
            }else{
                "开始直播"
            }
            InputUrlDialogFragment.createDialog(pb,{
                    _,_,url ->
                if (TextUtils.isEmpty(url)){
                    return@createDialog
                }
                if (isLiveStart){
                    liveStreamHelper.stop()
                    isLiveStart = false
                }else{
                    settings.lastPushUrl = url
                    //内部有重连机制，开发者只需要关注相关状态
                    liveStreamHelper.start(url)
                    isLiveStart = true
                }
            },"取消",{
                    _,_,_ ->
            },lastPushUrl).show(supportFragmentManager,"action_url")
        }

        val url = settings.lastUrl
        //使用硬解
        fpvWidget?.usingMediaCodec = true

        //使用软解
//        fpvWidget?.usingMediaCodec = false

        //设置播放地址
        fpvWidget?.url = if (TextUtils.isEmpty(url)) Settings.C10 else url

        //使用云卓播放器
        fpvWidget?.playerType = PlayerType.ONLY_SKY

        //RTSP流TCP/UDP连接
        fpvWidget?.rtspTranstype = RtspTransport.AUTO

        mapWidget?.setOnClickListener {
            if (isFullVideo){
                switchVideoMap()
            }
        }
        fpvWidget?.setOnClickListener {
            if (!isFullVideo){
                switchVideoMap()
            }
        }

        fpvWidget?.videoDecoderCallBack = object : VideoDecoderCallBack{
            override fun onYUV(data: ByteBuffer, width: Int, height: Int, pixel_format: Int) {
                mp4RecordHelper.putYUV(data,width, height, pixel_format)
                liveStreamHelper.putYUV(data,width, height, pixel_format)
            }
        }

        //设置直播流状态监听器
        liveStreamHelper.addListener(liveStreamListener)

        /**
         * 配置编码器相关属性
         */
        liveStreamHelper.bitrate = 1000000 //比特率
        liveStreamHelper.frameRate = 15 //输出帧率
        liveStreamHelper.setVideoSize(640,360) //输出分辨率
        liveStreamHelper.isUseSoftEncoder = true //true:软编码（X264），false:硬编码

        btnRecordVideo?.setOnClickListener {
            if (!isStartRecord){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
                    if (Environment.isExternalStorageManager()){
                        startRecord()
                    }else{
                        startActivity(Intent(android.provider.Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION))
                    }
                }else{
                    startRecord()
                }
            }else{
                mp4RecordHelper.stop {
                    it?.let {
                        MyLogger.kLog().e("停止录像失败:${it}")
                    }
                    isStartRecord = false
                    switchRecordText()
                }
            }
        }

        //开始播放
        fpvWidget?.start()
    }

    private fun startRecord() {
        checkStoragePermissions(1001,object : PermissionsResultCallback{
            override fun onGranted() {
                mp4RecordHelper.bitrate = 1500000 //比特率
                mp4RecordHelper.frameRate = 15 //输出帧率
                mp4RecordHelper.setVideoSize(1280,720) //输出分辨率
                mp4RecordHelper.isUseSoftEncoder = true //true:软编码（X264），false:硬编码
                val ret = mp4RecordHelper.start("${Environment.getExternalStorageDirectory()}/${Environment.DIRECTORY_DOWNLOADS}/${System.currentTimeMillis()}.mp4")
                if (ret == null){
                    isStartRecord = true
                    switchRecordText()
                }
                ret?.let {
                    MyLogger.kLog().e("开始录像失败:${it}")
                }
            }

            override fun onDenied(permissions: Array<out String>?) {
                //没权限
            }

            override fun onError(e: Throwable?) {
                //异常
            }

        })
    }

    private fun switchRecordText(){
        if (isStartRecord){
            btnRecordVideo?.text = "停止录像"
        }else{
            btnRecordVideo?.text = "开始录像"
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //停止播放
        fpvWidget?.stop()
        liveStreamHelper.removeListener(liveStreamListener)
        if (isLiveStart){
            liveStreamHelper.stop()
            isLiveStart = false
        }

        if (isStartRecord){
            mp4RecordHelper.stop {
                it?.let {
                    MyLogger.kLog().e("停止录像失败:${it}")
                }
                isStartRecord = false
                switchRecordText()
            }
        }
    }

    private var isFullVideo = false
    fun switchVideoMap() {
        if (isFullVideo){
            //设置交换图层后的宽高
            val fpvLayoutParams = fpvWidget?.layoutParams as? FrameLayout.LayoutParams
            fpvLayoutParams?.width = PxUtils.dp2px(this,240)
            fpvLayoutParams?.height = PxUtils.dp2px(this,135)
            fpvLayoutParams?.gravity = Gravity.BOTTOM or Gravity.START
            fpvWidget?.layoutParams = fpvLayoutParams
            val mapLayoutParams = mapWidget?.layoutParams as? FrameLayout.LayoutParams
            mapLayoutParams?.width = ViewGroup.LayoutParams.MATCH_PARENT
            mapLayoutParams?.height = ViewGroup.LayoutParams.MATCH_PARENT
            mapWidget?.layoutParams = mapLayoutParams
            //交换图层
            switchVideoMapLayout?.removeView(fpvWidget)
            switchVideoMapLayout?.addView(fpvWidget)
            isFullVideo = false
        }else{
            //设置交换图层后的宽高
            val fpvLayoutParams = fpvWidget?.layoutParams as? FrameLayout.LayoutParams
            fpvLayoutParams?.width = ViewGroup.LayoutParams.MATCH_PARENT
            fpvLayoutParams?.height = ViewGroup.LayoutParams.MATCH_PARENT
            fpvWidget?.layoutParams = fpvLayoutParams
            val mapLayoutParams = mapWidget?.layoutParams as? FrameLayout.LayoutParams
            mapLayoutParams?.width = PxUtils.dp2px(this,240)
            mapLayoutParams?.height = PxUtils.dp2px(this,135)
            mapLayoutParams?.gravity = Gravity.BOTTOM or Gravity.START
            mapWidget?.layoutParams = mapLayoutParams
            //交换图层
            switchVideoMapLayout?.removeView(mapWidget)
            switchVideoMapLayout?.addView(mapWidget)
            isFullVideo = true
        }
    }

    /**
     * 检查存储权限
     * @param result
     */
    fun checkStoragePermissions(requestCode:Int,result: PermissionsResultCallback?) {
        PermissionManager.getInstance()
            .checkPermissions(this, requestCode, result,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionManager.getInstance()
            .onRequestPermissionsResult(requestCode, permissions, grantResults)
    }


}